<template>
  <div class="page-workflow">
    <div v-if="!logDetailsShow" class="page-model">
      <input type="text" class="aimind-hidden-input" />
      <input type="password" class="aimind-hidden-input" />

      <div class="content">
        <div class="top-btn">
          <Input
            autocomplete="off"
            class="search"
            placeholder="请输入工作流名称"
            :search="true"
            v-model.trim="searchValue"
            @on-search="getPipelineSearch"
          />
          <Button @click="addNewLine=true" type="primary">新建工作流</Button>
        </div>
        <div class="content-table">
          <Table :columns="pipelinecolumns" :data="pipelineList">
            <template slot-scope="{ row }" slot="name">
              <span
                :title="row.name"
                class="pipeline-name ellipsis table-span-ellipsis"
                @click="toDrawer(row)"
              >{{ row.name }}</span>
            </template>
            <template slot-scope="{ row }" slot="createTime">
              <span v-if="row.createTime">{{ formatDateByStringMatch(row.createTime) }}</span>
              <span v-else>NA</span>
            </template>
            <template slot-scope="{ row }" slot="successTime">
              <span
                v-if="row.successTime"
                class="icon-position"
              >{{ formatDateByStringMatch(row.successTime) }}</span>
              <span v-else class="icon-position">NA</span>
              <i
                v-if="row.successTime"
                class="iconfont icon-talk"
                title="运行记录"
                @click="viewLogDetails(row, 'successId')"
              ></i>
            </template>
            <template slot-scope="{ row }" slot="failTime">
              <span
                v-if="row.failTime"
                class="icon-position"
              >{{ formatDateByStringMatch(row.failTime) }}</span>
              <span v-else class="icon-position">NA</span>
              <i
                v-if="row.failTime"
                class="iconfont icon-talk"
                title="运行记录"
                @click="viewLogDetails(row, 'failId')"
              ></i>
            </template>
            <template slot-scope="{ row }" slot="status">
              <div class="status">
                <span v-if="row.status" :class="['status-dot', row.status.toLowerCase()]"></span>
                <span>{{ translateStatus(row.status) }}</span>
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="action" class="action">
              <span @click="copy(row)" class="table-blue click-action">复制</span>
              <span @click="edit(row)" class="table-blue click-action">编辑</span>
              <span
                @click="start(row,index)"
                class="table-green click-action"
                v-show="row.status!=='RUNNING'"
              >启动</span>
              <span
                @click="stop(row,index)"
                class="table-red click-action"
                v-show="row.status==='RUNNING'"
              >停止</span>
              <span @click="viewHistory(row)" class="table-green click-action">查看历史</span>
              <span @click="delConfirm('info', index, row.status)" class="table-red click-action">删除</span>
            </template>
          </Table>
        </div>

        <Page
          style="margin-bottom: 10px;"
          v-show="pagination.total > pagination.pageSize || pagination.pageSize > 10"
          @on-change="changePageNum"
          @on-page-size-change="changePageSize"
          :total="pagination.total"
          :current="pagination.current"
          :page-size="pagination.pageSize"
          :transfer="true"
          show-sizer
          show-total
        />
      </div>
      <div>
        <Modal v-model="addNewLine" title="新建工作流" draggable width="460px" class="line-modal">
          <div class="line-content">
            <Form
              ref="addForm"
              :model="modelAdd"
              :label-width="100"
              :rules="ruleAdd"
              label-position="left"
            >
              <FormItem label="工作流名称：" prop="name">
                <Input
                  placeholder="请输入名称"
                  class="workflow-input-width"
                  :maxlength="20"
                  v-model.trim="modelAdd.name"
                />
              </FormItem>
              <FormItem label="工作流备注：" prop="desc" class="desc-textarea">
                <Input
                  type="textarea"
                  class="form-textarea"
                  placeholder="请输入工作流备注"
                  :maxlength="150"
                  v-model.trim="modelAdd.desc"
                />
              </FormItem>
            </Form>
          </div>
          <div slot="footer">
            <Button @click="cancel">取消</Button>
            <Button type="primary" @click="addPipeline">确定</Button>
          </div>
        </Modal>
        <Modal v-model="editLine" title="工作流信息" width="460px" class="edit-modal">
          <div class="edit-line-content">
            <Form
              ref="pipelineInfoForm"
              :model="editParams"
              :label-width="100"
              :rules="ruleEdit"
              label-position="right"
            >
              <FormItem label="工作流名称：" prop="name">
                <div class="edit-name">
                  <Input
                    v-if="showEditInput"
                    placeholder="请输入名称"
                    :maxlength="20"
                    class="workflow-input-width"
                    v-model.trim="editParams.name"
                  />
                  <div
                    :title="editParams.name"
                    v-if="!showEditInput"
                    class="name-width ellipsis"
                  >{{editParams.name}}</div>
                  <i class="iconfont icon-edit" @click="showEditInput=!showEditInput"></i>
                </div>
              </FormItem>
              <FormItem label="状态：" prop="status">
                <div class="edit-status">
                  <span
                    class="status-span"
                    v-if="editParams.status"
                    :class="editParams.status.toLowerCase()"
                  ></span>
                  {{translateStatus(editParams.status)}}
                </div>
              </FormItem>
              <FormItem label="创建时间：" prop="createTime">
                <div>{{formatDateByStringMatch(editParams.createTime)}}</div>
              </FormItem>
              <FormItem label="上次成功时间：" prop="successTime">
                <div
                  v-if="editParams.successTime"
                >{{formatDateByStringMatch(editParams.successTime)}}</div>
                <span v-else class="icon-position">NA</span>
              </FormItem>
              <FormItem label="工作流备注：" prop="desc">
                <Input
                  type="textarea"
                  class="form-textarea"
                  placeholder="请输入工作流备注"
                  :maxlength="150"
                  v-model.trim="editParams.desc"
                />
              </FormItem>
            </Form>
          </div>
          <div slot="footer">
            <Button @click="editCancel">取消</Button>
            <Button type="primary" @click="editPipeline">确定</Button>
          </div>
        </Modal>
        <Modal v-model="runHistory" :title="runHistoryTitle" width="800" class="history-modal">
          <div class="history-table">
            <div class="table">
              <Table :columns="taskColumns" :data="pipelineTaskLog">
                <template slot-scope="{ row }" slot="pipelineJobSt">
                  <span>{{formatDateByStringMatch(row.pipelineJobSt)}}</span>
                </template>
                <template slot-scope="{ row }" slot="pipelineJobFt">
                  <span>{{formatDateByStringMatch(row.pipelineJobFt)}}</span>
                </template>
                <template slot-scope="{ row }" slot="status">
                  <span>{{translateStatus(row.pipelineJobStatus)}}</span>
                </template>
                <template slot-scope="{ row }" slot="action">
                  <span
                    v-if="row.pipelineJobStatus!=='RUNNING'"
                    @click="viewLogDetails(row)"
                    class="table-blue"
                  >查看</span>
                </template>
              </Table>
              <Page
                style="margin-top: 10px;"
                v-if="paginationModal.total > paginationModal.pageSize || paginationModal.pageSize > 10"
                @on-change="changePageNumModal"
                @on-page-size-change="changePageSizeModal"
                :total="paginationModal.total"
                :current="paginationModal.current"
                :page-size="paginationModal.pageSize"
                transfer
                show-sizer
                show-total
              />
            </div>
          </div>
        </Modal>
      </div>
    </div>
    <div v-if="logDetailsShow">
      <log-details
        :pipelineJobId="pipelineJobId"
        :icon="icon"
        :pipelineJobName="pipelineJobName"
        v-on:back="back"
      ></log-details>
    </div>
  </div>
</template>

<script>
import LogDetails from './LogDetails';
import {
  addPipeline,
  getPipeline,
  editPipeline,
  delPipeline,
  pipelineJobs,
  copy,
  runPipeline,
  stopPipeline
} from 'http/api/pipeline';

import { formatDateByStringMatch, routePathData } from 'assets/scripts/common';
import { defaultIcon } from 'assets/scripts/code';
export default {
  components: {
    LogDetails
  },

  data () {
    return {
      defaultIcon: defaultIcon,
      addNewLine: false,
      showEditInput: false,
      logDetails: true,
      editLine: false,
      runHistory: false,
      logDetailsShow: false,
      pipelineJobName: '',
      searchValue: '',
      atlaName: '',
      kgId: '',
      icon: '',
      pipelineJobId: '',
      pipelineList: [],
      runHistoryTitle: '影视关系抽取 运行历史',
      pagination: {
        total: 10,
        current: 1,
        pageSize: 10
      },
      paginationModal: {
        total: 10,
        current: 1,
        pageSize: 10
      },
      modelAdd: {
        desc: '',
        name: ''
      },
      pipelinecolumns: [
        {
          title: '工作流名称',
          slot: 'name',
          tooltip: true,
          minWidth: 120
        },
        {
          title: '创建时间',
          key: 'createTime',
          slot: 'createTime',
          minWidth: 180
        },
        {
          title: '上次成功时间',
          key: 'successTime',
          slot: 'successTime',
          minWidth: 210
        },
        {
          title: '上次失败时间',
          key: 'failTime',
          slot: 'failTime',
          minWidth: 210
        },
        {
          title: '状态',
          key: 'status',
          slot: 'status',
          minWidth: 120
        },
        {
          title: '操作',
          slot: 'action',
          minWidth: 240
        }
      ],
      taskColumns: [
        {
          title: '开始时间',
          key: 'pipelineJobSt',
          slot: 'pipelineJobSt',
          width: 220
        },
        {
          title: '结束时间',
          key: 'pipelineJobFt',
          slot: 'pipelineJobFt',
          width: 220
        },
        {
          title: '状态',
          key: 'pipelineJobStatus',
          slot: 'status',
          width: 137
        },
        {
          title: '操作',
          slot: 'action',
          width: 140
        }
      ],
      editParams: {
        name: '',
        createTime: '',
        successTime: '',
        failTime: '',
        successId: '',
        failId: '',
        status: '',
        desc: 'just test',
        id: ''
      },
      ruleAdd: {
        name: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          },
          {
            max: 100,
            message: '长度不超过100',
            trigger: 'blur'
          }
        ],
        desc: [
          {
            max: 150,
            message: '长度不超过150',
            trigger: 'blur'
          }
        ]
      },
      ruleEdit: {
        name: [
          {
            required: true,
            message: '名称不能为空',
            trigger: 'blur'
          },
          {
            max: 100,
            message: '长度不超过100',
            trigger: 'blur'
          }
        ],
        desc: [
          {
            max: 150,
            message: '长度不超过150',
            trigger: 'blur'
          }
        ]
      },
      pipelineTaskLog: [],
      rowHistory: null,
      formatDateByStringMatch: formatDateByStringMatch,
      runIds: {} // 记录工作流运行的id
    };
  },

  methods: {
    translateStatus (status) {
      let result = 'NA';
      if (status === 'RUNNING') {
        result = '进行中';
      } else if (status === 'SUCCESS') {
        result = '成功';
      } else if (status === 'FAIL') {
        result = '失败';
      }
      return result;
    },

    edit (row) {
      this.$set(this.editParams, 'name', row.name);
      this.$set(this.editParams, 'failTime', row.failTime);
      this.$set(this.editParams, 'failId', row.failTime);
      this.$set(this.editParams, 'createTime', row.createTime);
      this.$set(this.editParams, 'successTime', row.successTime);
      this.$set(this.editParams, 'successId', row.successId);
      this.$set(this.editParams, 'status', row.status);
      this.$set(this.editParams, 'id', row.id);
      this.$set(this.editParams, 'desc', row.desc);
      this.editLine = true;
    },
    copy (row) {
      this.$Modal.confirm({
        title: '确认复制该工作流吗？',
        // content: '<p>' + delInfo + '</p>',
        onOk: () => {
          copy({
            id: row.id
          }).then(res => {
            this.getPipeline();
          });
        },
        onCancel: () => {
          // this.$Message.info('Clicked cancel');
        }
      });
    },
    // 添加工作流列表
    addPipeline () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.modelAdd.name = this.modelAdd.name.trim();
          if (!this.modelAdd.name) {
            this.$Message.error('名称不能为空');
            return;
          }
          addPipeline({
            name: this.modelAdd.name,
            kgId: this.kgId,
            desc: this.modelAdd.desc
          }).then(res => {
            if (res) {
              this.modelAdd.name = '';
              this.modelAdd.desc = '';
              this.addNewLine = false;
              this.getPipeline();
            }
          });
        }
      });
    },

    // 编辑工作流
    editPipeline () {
      this.$refs.pipelineInfoForm.validate(valid => {
        if (valid) {
          this.editParams.name = this.editParams.name.trim();
          if (!this.editParams.name) {
            this.$Message.error('名称不能为空');
            return;
          }
          editPipeline({
            id: this.editParams.id,
            name: this.editParams.name,
            desc: this.editParams.desc
          })
            .then(res => {
              if (res) {
                this.editLine = false;
                this.editParams = {};
                this.getPipeline();
              }
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },
    editCancel () {
      this.editLine = false;
    },
    // 删除工作流
    delPipeline (pipeline) {
      if (pipeline.status === 'RUNNING') {
        this.$Message.error('运行中的工作流不可删除');
        return;
      }
      delPipeline({
        id: pipeline.id
      }).then(res => {
        if (
          this.pagination.total > this.pagination.pageSize &&
          this.pagination.pageSize * (this.pagination.current - 1) + 1 ===
            this.pagination.total
        ) {
          this.pagination.current--;
        }
        if (res) {
          this.getPipeline();
        }
      });
    },
    getPipelineSearch () {
      this.pagination.current = 1;
      this.getPipeline();
    },
    // 查询工作流列表
    getPipeline () {
      let param = {
        kgId: this.kgId,
        name: this.searchValue,
        pageIndex: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      console.log(param);
      getPipeline(param).then(res => {
        if (res) {
          this.pagination.total = res.data.total;
          this.pipelineList = res.data.pipelineStates;
        }
      });
    },

    cancel () {
      this.addNewLine = false;
    },

    // 删除工作流
    delConfirm (type, index, status) {
      let delInfo = '确认要删除该工作流吗？';
      if (status === 'runing') {
        delInfo = '该工作流正在运行，请先前往画板页面进行关闭。';
      }
      this.$Modal.confirm({
        title: '删除工作流',
        content: '<p>' + delInfo + '</p>',
        onOk: () => {
          this.delPipeline(this.pipelineList[index]);
        },
        onCancel: () => {}
      });
    },

    // 查看历史
    viewHistory (row, pageModalChangeFlag) {
      this.rowHistory = row;
      if (!pageModalChangeFlag === true) {
        this.paginationModal.current = 1;
        this.paginationModal.pageSize = 10;
      }
      pipelineJobs({
        pipelineName: '',
        pipelineJobSt: '',
        pipelineJobFt: '',
        pipelineJobStatus: '',
        pipelineId: row.id,
        kgId: this.kgId,
        pageIndex: this.paginationModal.current,
        pageSize: this.paginationModal.pageSize
      }).then(res => {
        if (res) {
          this.pipelineTaskLog = res.data.pipelineJobDTOs;
          this.paginationModal.total = res.data.total;
          this.runHistoryTitle = row.name;
        } else {
          this.pipelineTaskLog = [];
        }
        this.runHistory = true;
      });
    },
    start (row, index) {
      this.$Modal.confirm({
        title: '启动工作流',
        content: '<p>' + '确定启动该工作流吗？' + '</p>',
        onOk: () => {
          runPipeline({
            id: row.id
          }).then(res => {
            if (res) {
              localStorage[`stopId${row.id}`] = res.data.id; // 防止刷新
              this.runIds[index] = res.data.id;
              this.$Message.success('启动成功');
              this.getPipeline();
            }
          });
        },
        onCancel: () => {}
      });
    },
    stop (row, index) {
      console.log(row)
      console.log(localStorage[`stopId${row.id}`], this.runIds[index])
      this.$Modal.confirm({
        title: '停止工作流',
        content: '<p>' + '确定停止工作流？' + '</p>',
        onOk: () => {
          stopPipeline({
            id: row.id
          }).then(res => {
            if (res) {
              delete localStorage[`stopId${row.id}`];
              this.$Message.success('已停止运行');
              this.getPipeline();
            }
          });
        },
        onCancel: () => {}
      });
    },
    toDrawer (row) {
      localStorage.setItem(`workflowInfo${row.id}`, JSON.stringify(row));
      window.open(
        `/#${routePathData.workflowdrawer}?id=${this.$route.query.id}&pipelineId=${row.id}`
      );
    },
    viewLogDetails (row, type) {
      // 查看具体日志
      this.logDetailsShow = true;
      this.pipelineJobId = row.pipelineJobId ? row.pipelineJobId : row[type];
      this.pipelineJobName = row.pipelineName ? row.pipelineName : row.name;
    },
    back () {
      this.logDetailsShow = false;
    },
    viewDetail (index) {},
    changePageNum (pageNum) {
      this.pagination.current = pageNum;
      this.getPipeline();
    },
    changePageNumModal (pageNum) {
      this.paginationModal.current = pageNum;
      this.viewHistory(this.rowHistory, true);
    },
    changePageSize (size) {
      this.pagination.pageSize = size;
      this.changePageNum(1);
    },
    changePageSizeModal (size) {
      this.paginationModal.pageSize = size;
      this.changePageNumModal(1);
    }
  },
  async mounted () {
    let id = this.$route.query.id;
    console.log(this.$route, this.$route.query)
    this.kgId = id;
    // await getAtlaName({
    //   id
    // }).then(res => {
    //   if (res) {
    //     this.atlaName = res.data.name;
    //     this.icon = res.data.icon;
    //     // localStorage.setItem('atlasIcon', this.icon);
    //   }
    // });
    this.searchValue = '';
    this.getPipeline();
  }
};
</script>

<style rel="stylesheet/less"  scoped lang="less" >
@import "../../assets/theme/themeBlue.less";
.page-workflow {
  .page-model {
    .header {
      padding: 0 25px 0;
      height: 60px;
      line-height: 60px;
      background: #fff;
      .img {
        width: 30px;
        height: 30px;
        margin: 0 10px;
        vertical-align: middle;
        position: relative;
        top: -3px;
      }
      .first-title {
        display: inline-block;
        vertical-align: middle;
        max-width: 300px;
      }
    }
    .content {
      width: 100%;
      margin-top: 20px;
      padding: 0 20px;
      box-sizing: border-box;
      .top-btn {
        margin-bottom: 20px;
        .search {
          width: 280px;
        }
        button {
          float: right;
        }
      }
      .content-table {
        margin-bottom: 10px;
        .status {
          .status-dot {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 4px;
            margin-right: 4px;
            position: relative;
            top: -2px;
            &.running {
              background: #0e77d1;
            }
            &.fail {
              background: #f04134;
            }
            &.success {
              background: #00a854;
            }
          }
        }
        .click-action {
          margin: 0 5px 0 5px;
          color: @primary;
          cursor: pointer;
        }
        .pipeline-name {
          color: @primary;
          cursor: pointer;
        }
      }
    }
  }
  .line-modal {
    background-color: rgba(255, 255, 255, 1);
    border-radius: 4px;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.149019607843137);
    font-size: 16px;
    .line-content {
      width: 100%;
      margin: 30px 0 0 40px;
      padding-right: 123px;
    }
  }
  .edit-modal {
    border-width: 0px;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 4px;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.149019607843137);
    font-size: 16px !important;
    color: rgba(0, 0, 0, 0.647058823529412);
    text-align: left;
    line-height: 24px;
    .edit-line-content {
      width: 100%;
      margin-left: 20px;
      align-items: center;
      padding-right: 103px;
      .edit-name {
        display: flex;
      }
      .edit-name i {
        margin-left: 15px;
      }
      .edit-line {
        display: flex;
        margin-top: 20px;
        font-size: 16px;
      }
      .edit-status {
        display: flex;
        align-items: center;
        .status-span {
          display: block;
          width: 8px;
          height: 8px;
          border-radius: 4px;
          margin-right: 10px;
        }
        .running {
          background: #0e77d1;
        }
        .fall {
          background: #f04134;
        }
        .success {
          background: #00a854;
        }
      }
    }
  }
  .history-modal {
    .history-table {
      margin: 0 0 0 15px;
      width: 730px;
      .table {
        height: 200px;
        overflow-y: auto;
        .pagination {
          padding-bottom: 20px;
          padding-top: 20px;
          display: flex;
          justify-content: center;
        }
      }
      .circle {
        display: block;
        width: 20px;
        height: 20px;
        border-radius: 10px;
        margin-left: 7px;
        background-color: red;
      }
      .circleBlue {
        background-color: #0078ff;
      }
      .show-log {
        color: #0078ff;
        cursor: pointer;
      }
    }
    .pagination {
      padding-bottom: 20px;
      padding-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
  .icon-talk {
    position: relative;
    top: 1px;
    left: 2px;
    color: #999999;
    cursor: pointer;
    &:hover {
      color: @primary;
    }
  }
}
</style>

<style  lang="less">
@import "../../assets/theme/themeBlue.less";
.line-modal {
  .line-content {
    .form-textarea textarea {
      height: 82px !important;
      width: 280px !important;
    }
    .workflow-input-width {
      width: 280px !important;
    }
  }
  .ivu-modal-body {
    padding-left: 40px;
  }
  .desc-textarea {
    margin-bottom: 4px;
  }
}

.edit-modal {
  .ivu-modal-body {
    padding-left: 40px;
  }
  .edit-line-content {
    .ivu-form-item {
      margin-bottom: 10px;
    }
    .form-textarea textarea {
      border-radius: 4px;
      height: 82px !important;
      width: 280px !important;
    }
    .workflow-input-width {
      width: 280px !important;
    }
    .icon-edit {
      cursor: pointer;
      position: relative;
      top: 3px;
      &:hover {
        color: @primary;
      }
    }
    .name-width {
      max-width: 90%;
      display: inline-block;
      vertical-align: middle;
    }
  }
}

.history-modal {
  .ivu-modal-body {
    padding: 20px 40px;
  }
}
</style>
